package com.wl.boot.batch.util;

import com.alibaba.excel.EasyExcel;
import com.wl.boot.batch.bean.entity.CommonExcelConfig;
import com.wl.boot.batch.bean.entity.CommonExcelPageField;
import com.wl.boot.batch.exception.ExcelException;
import com.wl.boot.batch.listener.ExcelListener;
import com.wl.boot.batch.service.impl.ExcelServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;

/**
 * @author wanglu
 */
public class EasyExcelUtil {
    private static final Logger logger = LoggerFactory.getLogger(EasyExcelUtil.class);

    private static final int DEFAULT_SHEETNO = 0;

    private static final int DEFAULT_ROWNO = 1;

    public static void main(String[] args) throws Exception {
        String fileName = "C:\\Users\\Administrator\\Desktop\\20W.xlsx";
        // 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
        long start = System.currentTimeMillis();
        System.out.println("开始解析：" + start);
        ExcelListener listener = new ExcelListener();
        EasyExcel.read(fileName, listener).sheet(DEFAULT_SHEETNO).doRead();
//        List result = listener.getDatas();
        long end = System.currentTimeMillis();
        System.out.println("解析耗时：" + (end - start) / 1000);
//        logger.info("数据量：" + result.size());
    }

    /**
     * 读取Excel
     *
     * @param file    上传的excel文件
     * @param ec      excel对应的配置文件
     * @param epf     excel对应的表配置
     * @param service 对应的service服务
     */
    public static List readExcel(MultipartFile file, CommonExcelConfig ec, List<CommonExcelPageField> epf, ExcelServiceImpl service) throws Exception {
        int sheetIndex = ec == null ? DEFAULT_SHEETNO : ec.getSheetIndex() - 1;
        int startRow = ec == null ? DEFAULT_ROWNO : ec.getStartRow() - 1;
        ExcelListener listener = new ExcelListener(service, epf, startRow, ec.getTargetTable());
        return readExcel(file, sheetIndex, listener);
    }

    /**
     * 读取
     *
     * @param file
     * @param sheetIndex
     * @param listener
     */
    private static List readExcel(MultipartFile file, int sheetIndex, ExcelListener listener) throws Exception {
        if (sheetIndex == 0) {
            // 循环全部页签
            EasyExcel.read(file.getInputStream(), listener).sheet().doRead();

        } else {
            readExcelSheet(file, sheetIndex, listener);
        }
        return listener.getDatas();
    }

    private static void readExcelSheet(MultipartFile file, int sheetIndex, ExcelListener listener) throws Exception {
        EasyExcel.read(file.getInputStream(), listener).sheet(sheetIndex).doRead();
    }


    public static void checkExcel(MultipartFile file) throws ExcelException {
        String filename = file.getOriginalFilename();
        if (filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"))) {
            throw new ExcelException("文件格式错误！");
        }
    }

    public static void checkExcels(MultipartFile[] files) {
        List<MultipartFile> list = Arrays.asList(files);
        Optional<MultipartFile> op = list.parallelStream().filter(f -> {
            String filename = f.getOriginalFilename();
            return filename == null || (!filename.toLowerCase().endsWith(".xls") && !filename.toLowerCase().endsWith(".xlsx"));
        }).findFirst();
        if (op.isPresent()) {
            throw new ExcelException("文件格式错误！");
        }
    }

}
